//
//  HLLoginInfoViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/24.
//

#import "HLLoginInfoViewController.h"
#import "HLLoginInfoFieldView.h"
#import "HLPickerManager.h"
#import "HLOSSManager.h"
#import "HLLoginOptionRequest.h"
#import <libOpenInstallSDK/OpenInstallSDK.h>

@interface HLLoginInfoViewController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) HLPickerManager *pickerManager;
@property (nonatomic, strong) HLOSSManager *ossManager;

@property (nonatomic, strong) HLLoginOptionRequest *randomRequest;
@property (nonatomic, strong) BRDatePickerView *datePickerView;
@property (nonatomic, strong) UIImage *uploadImage;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;

@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) QMUIButton *avatarButton;

@property (nonatomic, strong) UIStackView *infoContentView;
@property (nonatomic, strong) HLLoginInfoFieldView *nicknameFieldView;
@property (nonatomic, strong) HLLoginInfoFieldView *birthdayFieldView;
@property (nonatomic, strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic, strong) HLLoginInfoFieldView *inviteFieldView;

@property (nonatomic, strong) QMUIButton *saveButton;

@end

@implementation HLLoginInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getChannelCode];
    
    self.pickerManager = [[HLPickerManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto avatar:YES];
    self.ossManager = [[HLOSSManager alloc] initWithOSSPath:@"avatar"];
    
    self.randomRequest =[[HLLoginOptionRequest alloc] initWithType:HLLoginOptionTypeRandNickname params:@{@"sex":@"1"}];
    [_randomRequest startWithCompletionBlockWithSuccess:^(__kindof HLLoginOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            self.nicknameFieldView.textField.text = request.result[@"data"];
            [self updateSaveButtonEnable];
        }
    } failure:nil];
    
    NSDate *date = [NSDate date];
    self.datePickerView = [[BRDatePickerView alloc]init];
    _datePickerView.pickerMode = BRDatePickerModeYMD;
    _datePickerView.title = @"选择年月日";
    _datePickerView.selectValue = [self defaultSelectValue];
    _datePickerView.minDate = [NSDate br_setYear:1950 month:10 day:01];
    _datePickerView.maxDate = [NSDate br_setYear:date.br_year-18 month:date.br_month day:date.br_day];
    MJWeakSelf;
    _datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        NSString *selectedValue = [NSDate br_stringFromDate:selectDate dateFormat:@"yyyy-MM-dd"];
        weakSelf.birthdayFieldView.textField.text = selectedValue;
        weakSelf.datePickerView.selectValue = selectedValue;
        [weakSelf updateSaveButtonEnable];
    };
    _datePickerView.pickerStyle = [HLUIHelper pickerStyle];
}

- (NSString *)defaultSelectValue
{
    NSDate *date = [NSDate date];
    NSDate *current = [NSDate br_setYear:(date.br_year-20) month:date.br_month day:date.br_day];
    return [NSDate br_stringFromDate:current dateFormat:@"yyyy-MM-dd"];;
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"";
}

- (void)initSubviews
{
    [super initSubviews];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    self.headerView = [[UIImageView alloc] initWithImage:UIImageMake(@"login_info_header")];
    [self.view addSubview:_headerView];
    [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
    }];
    
    
    self.titleLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(24) textColor:HLTextColor1];
    _titleLabel.text = @"完善你的资料";
    [_contentView addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.top.mas_equalTo(NavigationContentTopConstant + 42);
    }];
    
    self.detailLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(16) textColor:HLTextColor2];
    _detailLabel.text = @"让大家更好地了解你";
    _detailLabel.numberOfLines = 0;
    [_contentView addSubview:_detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_titleLabel);
        make.top.equalTo(_titleLabel.mas_bottom).offset(8);
    }];
    
    CGFloat size = 126;
    self.avatarView = [[UIImageView alloc] init];
    _avatarView.layer.masksToBounds = YES;
    _avatarView.image = UIImageMake(@"login_avatar");
    _avatarView.layer.cornerRadius = size / 2;
    [_contentView addSubview:_avatarView];
    [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_detailLabel);
        make.size.mas_equalTo(size);
        make.top.equalTo(_detailLabel.mas_bottom).offset(20);
    }];
    
    self.avatarButton = [[QMUIButton alloc] init];
    [_avatarButton setImage:UIImageMake(@"login_avatar_button") forState:UIControlStateNormal];
    [_avatarButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_avatarButton];
    [_avatarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_avatarView);
        make.bottom.equalTo(_avatarView).offset(8);
    }];
    
    
    self.infoContentView = [[UIStackView alloc] init];
    _infoContentView.axis = UILayoutConstraintAxisVertical;
    _infoContentView.distribution = UIStackViewDistributionEqualSpacing;
    _infoContentView.alignment = UIStackViewAlignmentTop;
    _infoContentView.spacing = 20;
    [_contentView addSubview:_infoContentView];
    [_infoContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_detailLabel);
        make.top.equalTo(_avatarButton.mas_bottom).offset(20);
    }];
    
    self.nicknameFieldView = [[HLLoginInfoFieldView alloc] init];
    _nicknameFieldView.titleLabel.text = @"昵称";
    _nicknameFieldView.textField.placeholder = @"请输入或随机一个昵称";
    _nicknameFieldView.textField.delegate = self;
    _nicknameFieldView.textField.maximumTextLength = 16;
    [_nicknameFieldView.button setTitle:@"随机" forState:UIControlStateNormal];
    [_nicknameFieldView.button setImage:UIImageMake(@"login_random") forState:UIControlStateNormal];
    [_nicknameFieldView.button addTarget:self action:@selector(randomNicknameAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.birthdayFieldView = [[HLLoginInfoFieldView alloc] init];
    _birthdayFieldView.titleLabel.text = @"生日";
    _birthdayFieldView.textField.placeholder = @"请选择你的出生日期";
    _birthdayFieldView.textField.text = [self defaultSelectValue];
    _birthdayFieldView.textField.delegate = self;
    _birthdayFieldView.textField.enabled = NO;
    [_birthdayFieldView.button setImage:UIImageMake(@"login_selected") forState:UIControlStateNormal];
    [_birthdayFieldView.button addTarget:self action:@selector(selectDateAction) forControlEvents:UIControlEventTouchUpInside];
    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectDateAction)];
    [_birthdayFieldView addGestureRecognizer:_tapGesture];
    self.inviteFieldView = [[HLLoginInfoFieldView alloc] init];
    _inviteFieldView.titleLabel.text = @"邀请码";
    _inviteFieldView.textField.placeholder = @"请输入邀请码（非必填）";
    _inviteFieldView.textField.delegate = self;
    
    [_infoContentView addArrangedSubview:_nicknameFieldView];
    [_infoContentView addArrangedSubview:_birthdayFieldView];
    [_infoContentView addArrangedSubview:_inviteFieldView];
    
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_infoContentView.mas_bottom).offset(20);
    }];
    
    self.saveButton = [[QMUIButton alloc] init];
    _saveButton.titleLabel.font = UIFontMake(15);
    [_saveButton setTitle:@"开启美食之旅" forState:UIControlStateNormal];
    [_saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_saveButton setBackgroundColor:HLMainColor];
    _saveButton.cornerRadius = 12;
    _saveButton.enabled = NO;
    [_saveButton addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_saveButton];
    [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.height.mas_equalTo(50);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 12));
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:UIColorClear];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorBlack;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (void)saveAction:(QMUIButton *)btn
{

    if (self.uploadImage){
        MJWeakSelf;
        [self.ossManager uploadDatas:@[self.uploadImage] callBack:^(NSArray<NSString *> * urls) {
            if (urls.count > 0){
                NSString *url = urls.firstObject;
                [weakSelf saveRequestWithUrl:url];
            }
        }];
    } else {
        [self saveRequestWithUrl:@""];
    }
}

- (void)saveRequestWithUrl:(NSString *)url
{
    NSString *nickname = self.nicknameFieldView.textField.text;
    NSString *birthday = self.birthdayFieldView.textField.text;
    NSString *inviteNo = self.inviteFieldView.textField.text;
    NSDictionary *params = @{
        @"avatar":url,
        @"sex":@"1",
        @"nickName":nickname,
        @"birthday":birthday,
        @"otherInviteNo":inviteNo};
    self.request = [[HLLoginOptionRequest alloc] initWithType:HLLoginOptionTypeInfo params:params];
    self.request.delegate = self;
    [self.request start];
}

- (void)selectDateAction
{
    [_datePickerView show];
}

- (void)randomNicknameAction
{
    [_randomRequest startWithCompletionBlockWithSuccess:^(__kindof HLLoginOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            self.nicknameFieldView.textField.text = request.result[@"data"];
            [self updateSaveButtonEnable];
        }
    } failure:nil];
}

- (void)uploadAction
{
    MJWeakSelf;
    [self.pickerManager showWithController:self block:^(NSArray<HXPhotoModel *> *photos) {
        HXPhotoModel *photo = [photos firstObject];
        [photo getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
            weakSelf.avatarView.image = image;
            weakSelf.uploadImage = image;
            [weakSelf updateSaveButtonEnable];
        } failed:nil];
    }];
}

- (void)dateChangeAction:(UIDatePicker *)picker
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [formatter  stringFromDate:picker.date];
    self.birthdayFieldView.textField.text = dateStr;
}


- (void)updateSaveButtonEnable
{
    self.saveButton.enabled = (([self.nicknameFieldView.textField.text length] >= 2) && ( [self.birthdayFieldView.textField.text length] >= 3)); // self.uploadImage != nil
}

#pragma QMUITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string originalValue:(BOOL)originalValue
{
    [self updateSaveButtonEnable];
    return YES;
}

#pragma request
- (void)requestFinished:(__kindof HLLoginOptionRequest *)request
{
    [super requestFinished:request];
    
    if (request.isSuccess){
        HLLoginModel *login = [HLLoginModel dataWithKeychain];
        login.isInfoDone = 1;
        [login syncDataKeychain];
        [[HLRunTime shareInstance] loginWithData:login];
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    [super requestFailed:request];
}

- (void)getChannelCode
{
    [[OpenInstallSDK defaultManager] getInstallParmsCompleted:^(OpeninstallData * _Nullable appData) {
        //在主线程中回调
        if (appData.data) {//(动态安装参数)
          //e.g.如免填邀请码建立邀请关系、自动加好友、自动进入某个群组或房间等
        }
        if (appData.channelCode) {//(通过渠道链接或二维码安装会返回渠道编号)
           //e.g.可自己统计渠道相关数据等
        }
        NSString *logString = [NSString stringWithFormat:@"OpenInstallSDK:\n动态参数：%@;\n渠道编号：%@",appData.data,appData.channelCode];
        [QMUIConsole log:logString];
        NSString *code = appData.data[@"inviteCode"];
        self.inviteFieldView.textField.text = code;
        [[NSUserDefaults standardUserDefaults] setObject:code forKey:@"OPENINSTALL_INVITENO"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    
        
    }];
}

@end
